package cn.itcast.service.impl;

import cn.itcast.mapper.UserMapper;
import cn.itcast.pojo.Account;
import cn.itcast.service.Uservice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

@Service
public class UserServiceImpl implements Uservice {
    @Resource
    private UserMapper userMapper;

    @Override
    public List<Account> findAll() {
        List<Account> accountList = userMapper.findAll();
        return accountList;
    }

    @Override
    public Account findByName(String name) {
        Account account = userMapper.findByName(name);
        return account;
    }

    @Override
    public void update(Account account) {
        userMapper.update(account);
    }

    @Override
    public void delete(Integer id) {
        userMapper.delete(id);
    }

    @Override
    public void save(Account account) {
        userMapper.insert(account);
    }

    @Override
    @Transactional
    public void toMoneyByName(String outName, String inName, Double money) {

        //1.查询转出用户信息
        Account outAccount = userMapper.findByName(outName);
        //2.查询转入的信息
        Account inAccount = userMapper.findByName(inName);
        //3.转出账户减钱
        outAccount.setMoney(outAccount.getMoney() - money);
        //4.转入账户加钱
        inAccount.setMoney(inAccount.getMoney() - money);
        //5.更新转出账户
        userMapper.update(outAccount);
    //    int i = 1/0;
        //6.更新转入账户
        userMapper.update(inAccount);
    }
}
